define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock){

    var sysPath =  getServer() + "/static/app/fxpg/fxEconomicLossMiddleResult";

    var fxEconomyLossMiddleFormHtml = sysPath + "/views/fxEconomicLossMiddleResultForm.html";
	var getFxEconomyLossMiddleController = function(){
		return getServer() + "/fxEconomyLossMiddles";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		initProvinceSelect("山东省", "日照市", "岚山区");//"北京市", "北京市", "海淀区"
		
	};
    // 搜索栏省市区
    var initProvinceSelect = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#citySelect').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#areaSelect").append(htmlArea);
                                    $('#areaSelect').val(Area);
                                    // 列表
                                    createFxEconomyLossMiddleGrid();
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#areaSelect").append(htmlArea);
                                                    $('#areaSelect').val(Area);
                                                    createFxEconomyLossMiddleGrid();
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#citySelect").append(htmlCity);
                                    $('#citySelect').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
                $('#provinceSelect').val(Province);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };

	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
        	if($("#provinceSelect").val() == null){
        		Util.alert("请选择省");
                return;
        	}
        	if($("#citySelect").val() == null){
        		Util.alert("请选择市");
                return;
        	}
        	if($("#areaSelect").val() == null){
        		Util.alert("请选择区（县）");
                return;
        	}
            createFxEconomyLossMiddleGrid();
        });
        $("#btnReset").click(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
            initProvinceSelect("山东省", "日照市", "岚山区");//"北京市", "北京市", "海淀区"
		});
	};
	var createFxEconomyLossMiddleGrid= function() {
        $("#fxEconomyLossMiddleGrid").datagrid({
            url:getFxEconomyLossMiddleController() + "/getFxEconomyLossMiddles",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            columns:[[
				{
					field:'province',
					title:'省',
					width:'14%',
					align:'center',
				},
				{
					field:'city',
					title:'市',
					width:'14%',
					align:'center',
				},
				{
					field:'area',
					title:'区/县',
					width:'16%',
					align:'center'
				},
                {
                    field: 'earthquakeIntensity',
                    title: '烈度',
                    width: '12%',
                    align: 'center',
                    formatter: function (value) {
                        if (value == "6") {
                            return 'VI';
                        } else if (value == "7") {
                            return 'VII';
                        } else if (value == "8") {
                            return 'VIII';
                        } else if (value == "9") {
                            return 'IX';
                        } else if (value == "10") {
                            return 'X';
                        }
                    }
                },
				{
					field:'damageDegree',
					title:'破坏程度',
					width:'14%',
					align:'center',
					formatter: function (value) {
                        if (value == "0") {
                            return '基本完好';
                        } else if (value == "1") {
                            return '轻微破坏';
                        } else if (value == "2") {
                            return '中等破坏';
                        } else if (value == "3") {
                            return '严重破坏';
                        } else if (value == "4") {
                            return '完全破坏';
                        }
                    }
				},
				{
					field:'calculatedValue',
					title:'计算值（万元）',
					width:'14%',
					align:'center',
					//editor:{type:'numberbox',options:{precision:2}},
				    formatter:function(val,rowData,rowIndex){
                        if (val != null) {
                            var num = new Number(val) / 10000.0;
                            return num.toFixed(2);
                        }
				   	}
				},
				{
					field:'correctedValue',
					title:'修正值',
					width:'15%',
					align:'center',
					editor:{type:'numberbox',options:{precision:2}},
				    formatter:function(val,rowData,rowIndex){
                        if (val != null) {
                            var num = new Number(val);
                            return num.toFixed(2);
                        }
				   	}
				}
            ]],
            toolbar: [/*{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addFxEconomyLossMiddle();
                }
            }, */{
				iconCls: 'fa fa-plus-circle',
				text: "模板",
				handler: function () {
					downloadTemplate();
                    //alert("功能暂未实现");
				}
			}, {
				iconCls: 'fa fa-upload',
				text: "导入",
				handler: function () {
					importForm();
                    //alert("功能暂未实现");
				}
			}, {
				iconCls: 'fa fa-download',
				text: "导出",
				handler: function () {
					exportForm();
                    //alert("功能暂未实现");
				}
			},/*{
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteFxEconomyLossMiddle();
                }
            }*/],
            onClickCell: function (index, field, value) {
                if (endEditing()) {
                    $('#fxEconomyLossMiddleGrid').datagrid('selectRow', index).datagrid('editCell', {
                        index: index,
                        field: field
                    });
                    editIndex = index;
                    mergeCells("fxEconomyLossMiddleGrid", "province,city,area,earthquakeIntensity");
                }
            }, 
//          onDblClickCell: function (index, field, value) {
//				$("#fxEconomyLossMiddleGrid").datagrid('endEdit', index);
//				debugger;
//				mergeCells("fxEconomyLossMiddleGrid", "province,city,area,structureType");
//        	},
            onAfterEdit: function (index, row, changes) {
//             $("#fxEconomyLossMiddleGrid").datagrid('endEdit', index);
//			    $.ajax({
//			        url : '要改变后台数据的controller路径?fieId1='+row.属性1,
//			        data:{fieId2:row.fieId}, //额外的参数
//			        dataType: "text",//响应结果为文本
//			        success:function (data) {
//			            $.messager.alert('消息', data);
//			        }
//			    });
				//console.log(index, row, changes);
	            $.ajax({
	                url: getFxEconomyLossMiddleController(),
	                contentType: "application/json",
	                data: JSON.stringify(row),
	                type: "put",
	                success: function (data) {
	                    Util.alert(data.message);
	                    createFxEconomyLossMiddleGrid();
	                }
	            });
                
            },
            onLoadSuccess: function (data) {
                //垂直合并单元格
                mergeCells("fxEconomyLossMiddleGrid", "province,city,area,earthquakeIntensity");
            },
            queryParams:{
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
            },
//          pagination: true,
//          pageSize: 10
        });
    };
    // 模板下载
    var downloadTemplate= function () {
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/经济损失风险评估-中间结果管理模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });
    }
    // 导入
    var importForm = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/经济损失风险评估-中间结果管理模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxEconomyLossMiddleController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                    createFxEconomyLossMiddleGrid();
                }
            });
        });
    };
    /**
     * 导出
     */
    var exportForm = function () {
        var province= $("#provinceSelect").val();
        var city= $("#citySelect").val();
        var  area= $("#areaSelect").val();
        window.location.href = getFxEconomyLossMiddleController() + "/exportEconomyLoss?province=" + province + "&city=" + city+ "&area=" + area;
    };

    $.extend($.fn.datagrid.methods, {
        editCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat(
                    $(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });
    var editIndex = undefined;

    //结束编辑
    function endEditing() {
        if (editIndex == undefined) {
            return true
        }
        if ($('#fxEconomyLossMiddleGrid').datagrid('validateRow', editIndex)) {
            $('#fxEconomyLossMiddleGrid').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };

    //合并单元格方法
    /**
     * EasyUI DataGrid根据字段动态合并单元格
     * @param colList 要合并table的id, 此例子中是tTable
     * @param colList 要合并的列,多个列用逗号分隔(例如："tempParam,flowCode,queryParam");
     */
    function mergeCells(tableID, colList) {
        var colArray = colList.split(",");
        var tTable = $("#" + tableID);
        var tableRows = tTable.datagrid("getRows");
        var tableRowCnts = tableRows.length;
        var rowspan;
        var preTxt = "";
        var curTxt = "";
        for (j = colArray.length - 1; j >= 0; j--) {
            preTxt = "";
            rowspan = 1;
            for (i = 0; i <= tableRowCnts; i++) {
                if (i == tableRowCnts) {
                    curTxt = "";
                } else {
                    curTxt = tableRows[i][colArray[j]];
                }
                if (preTxt == curTxt) {
                    rowspan += 1;
                } else {
                    tTable.datagrid("mergeCells", {
                        index: i - rowspan,
                        field: colArray[j],//合并字段
                        rowspan: rowspan,
                        colspan: null
                    });
                    rowspan = 1;
                }
                preTxt = curTxt;
            }
        }
    };
	var getFxEconomyLossMiddle = function(id){
		$.ajax({
			url: getFxEconomyLossMiddleController() + "/"+id,
			type: "get",
			success: function (data) {
				Tool.deserialize("fxEconomicLossMiddleResultForm", data);
			}
		});
	};


	window._editFxEconomyLossMiddle = function(fxEconomyLossMiddleId) {
		var slidebar = Util.slidebar({
			url: fxEconomyLossMiddleFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {
				//initProvinceSelectFrom();
				//initCitySelectFrom();
				//initAreaSelectFrom();
				//initEarthquakeIntensitySelectFrom();
				//initDamageDegreeSelectFrom();
				formValidator();
				getFxEconomyLossMiddle(fxEconomyLossMiddleId);
				$("#saveBtn").on("click", function () {
					if($("#fxEconomicLossMiddleResultForm").valid()){
						var data = Tool.serialize("fxEconomicLossMiddleResultForm");
						$.ajax({
							url: getFxEconomyLossMiddleController(),
                            contentType:"application/json",
                            data: JSON.stringify(data),
							type: "put",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
								createFxEconomyLossMiddleGrid();
							}
						});
					}
				});
			}
		});
	};
	var deleteFxEconomyLossMiddle = function() {
		var rows = $("#fxEconomyLossMiddleGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.id + ",";

			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getFxEconomyLossMiddleController() ,
				data: {
					ids : ids
				},
				type: "delete",
				success: function (data) {
					createFxEconomyLossMiddleGrid();
				}
			});
		}, function() {
			return;
		});

	};

	return {
		init:init
	};
});
